package org.huamoxi.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.huamoxi.constant.ResponseStatusConstants;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomExceptionPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        Throwable cause = e.getCause();
        if(cause instanceof InvalidTokenException) {
            map.put("code", ResponseStatusConstants.INVALID_CODE);//401
            map.put("msg", "无效的token");
        } else {
            map.put("code", ResponseStatusConstants.NOT_LOGIN_CODE);//401
            map.put("msg", "访问此资源需要完全的身份验证");
        }
        map.put("data", "请求路径是" + req.getServletPath());

        resp.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(resp.getOutputStream(), map);
    }
}
